package com.oneplatform.filter.prehandler;

import java.net.URI;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest.Builder;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;

import com.mendmix.common.CurrentRuntimeContext;
import com.mendmix.gateway.filter.PreFilterHandler;
import com.mendmix.gateway.model.BizSystemModule;

public class SystemIdQueryParamHandler implements PreFilterHandler {

	@Override
	public Builder process(ServerWebExchange exchange, BizSystemModule module, Builder requestBuilder) {

		String systemId = CurrentRuntimeContext.getSystemId();
		if (systemId != null) {
			// 默认设置查询参数
			MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();

			if (!queryParams.containsKey("systemId")) {
				URI uri = exchange.getRequest().getURI();
				StringBuilder query = new StringBuilder();
				String originalQuery = uri.getRawQuery();

				if (StringUtils.isNotBlank(originalQuery)) {
					query.append(originalQuery);
					if (originalQuery.charAt(originalQuery.length() - 1) != '&') {
						query.append('&');
					}
				}

				query.append("systemId");
				query.append('=');
				query.append(systemId);

				URI newUri = UriComponentsBuilder.fromUri(uri).replaceQuery(query.toString()).build(true).toUri();
				requestBuilder.uri(newUri);
			}
		}
		return requestBuilder;
	}

	@Override
	public int order() {
		return 1;
	}

}
